import React from 'react'
import { createForm } from 'rc-form'
import { actions } from 'mirrorx'
import { List, WhiteSpace, InputItem, Flex, ImagePicker } from 'antd-mobile'
import lrz from 'lrz'
import { API } from '../api'
import {Globle} from './Dictionaries'

const ListItem = List.Item

class App extends React.Component {
  constructor (props) {
    super(props)
    const Lang = window.LangMessage || {}
    this.state = {
      idcard: Lang.please_select || '请选择',
      zdcard: Lang.please_select || '请选择',
      invoice: Lang.please_select || '请选择',
      docList: [],
      files: [],
      filedata: [],
      multiple: false,
      errorMap: {},
      imageData: [],
      isMobileDevice: false
    }
    this.policyNo = T.urlQuery('policyNo')
    this.reportNo = T.urlQuery('reportNo')
    this.keyCodes = [{
      keycode: 'cardHolder',
      text: Lang.web_card_holder || 'Card Holder',
      rules: [
        { required: true, message: 'Please input name' }
      ]
    }, {
      keycode: 'accountNo',
      text: 'Bank Account',
      rules: [
        { required: true, message: 'Please input bank account' },
        { pattern: /^[0-9\s]*$/, message: 'The bank account is not valid' }
      ]
    }, {
      keycode: 'bankName',
      text: 'Bank',
      rules: [
        { required: true, message: 'Please input bank' }
      ]
    }]
    this.handleSubmit = this.handleSubmit.bind(this)
    this.onErrorClick = this.onErrorClick.bind(this)
    this.dealImage = this.dealImage.bind(this)
    this.uploadImage = this.uploadImage.bind(this)
    this.onChange = this.onChange.bind(this)
    this.getFiles = this.getFiles.bind(this)
    this.validateImageData = this.validateImageData.bind(this)

    //----> 上一步数据信息
    this.infoValues = JSON.parse(T.sessionStorage.get('infoValues')) || {}
    const claimType = this.infoValues['claimType'] || []
    const insuredId =  this.infoValues['insuredId'] || []
    const accidentDate = new Date(this.infoValues['accidentDate']) || new Date()
    this.infoValues['claimType'] = claimType.join('')
    this.infoValues['insuredId'] = insuredId.join('')
    this.infoValues['accidentDate'] = T.formatDate(Globle.datePormat, accidentDate) 
    //是否是健康险
    this.isHealth = this.infoValues.claimType == '2';

    this.FileModel = {
      identificationImageList: [], // 身份证明图片列表
      medicalCertificateImageList: [], // 诊断书（健康）图片列表
      medicalReceiptImageList: [], // 病历卡（健康）图片列表
      lossImageList: [], // 损失清单（财产）图片列表
      lossReportImageList: [], // 原始损失或损害报告（财产）图片列表
      otherImageList: [] // 其他图片列表
    }
  }

  componentDidMount () {

  }

  dealImage () {
    var formData = new FormData()
    const filedata = this.state.filedata
    let files = []
    for (var i = 0; i < filedata.length; i++) {
      files = filedata[i].files
      for (var n = 0, length = files.length; n < length; n++) {
        formData.append('file' + filedata[i].type, files[n].file)
      }
    }
    this.uploadImage(formData)
  }

  //
  /**
   * 拼装上传数据结构
   * @param {*} fileType 文件类型 1 2 3 4
   * @param {*} doType 操作类型 add增加 remove删除
   * @param {*} fileIndex 文件索引
   * @param {*} upModel 接口返回模型
   * @returns
   * @memberof App
   */
  swichUpType =(fileType, doType, fileIndex,upModel)=> {
    
    let fileList = []
    switch (fileType) {
      case 1:
        fileList = this.FileModel.identificationImageList        
        break
      case 2:
        fileList =this.isHealth ? this.FileModel.medicalCertificateImageList : this.FileModel.lossImageList
        break
      case 3:
        fileList = this.isHealth ? this.FileModel.medicalReceiptImageList : this.FileModel.lossReportImageList
        break
      case 4:
        fileList = this.FileModel.otherImageList
        break
    }
    if (doType == 'add'){
      fileList.push(upModel)
    }
    else {
      fileList.splice(fileIndex,1)
    }
  }

  uploadImage (formData, fileName, type) {
     formData.append('description', 'claimImageFile')
     console.log(formData.get('file'))
    // T.fetchFusion({// 上传图片
    //   url: '/fusion/uploadFile',
    //   loading: true,
    //   data: formData
    // }).then((res) => {
    //   if (res.success) {
    //     // T.showSuccess(window.LangMessage.upload_success || '上传成功')
    //     let imageCode = res.value || ''
    //     this.dealFileCodes(type, imageCode, fileName)
    //   } else {
    //     T.showError('Upload failed')
    //   }
    // })
    // 新版本文件上传
    const upFileDTO = T.fetch2({
      domainType:'apiclaim',
      url: API.fileUpload.path,
      loading: true,
      data: formData
    })
    upFileDTO.then((model) => {
      const upFileModel = model.data
      this.dealFileCodes(type, upFileModel.imageCode, fileName)
      //增加文件模型
      this.swichUpType(type,'add',0,upFileModel)
    })
  }

  dealFileCodes (type, imageCode, imageName) { // 处理文件code
    let imageData = this.state.imageData
    let hasType = false
    for (let i = 0; i < imageData.length; i++) {
      if (type == imageData[i].imageDocType) {
        hasType = true
        imageData[i].fileArray.push({ imageCode: imageCode, imageName: imageName })
      }
    }
    if (!hasType) {
      imageData.push({
        imageDocType: type,
        fileArray: [{ imageCode: imageCode, imageName: imageName }]
      })
    }
    this.setState({
      imageData
    })
  }

  onChange (files, type, index, code) {
    console.info(files, type, index, code)
    //限制文件大小为5M
    const currSize = files[files.length-1].file.size
    if (files && currSize){
       const fileMSize = currSize/1000/1024
       console.log('当前文件大小:'+fileMSize)
       if (fileMSize >= 5){
        T.showError('File must not exceed 5M')
        return false;
       }
    }
    // type 有add 添加 和 remove 移除 , index是图片索引
    let { filedata, imageData } = this.state
    let curIndex = files.length - 1 || 0

    for (var i = 0; i < filedata.length; i++) {
      if (code == filedata[i].type) {
        filedata.splice(i, 1)
        break
      }
    }

    if (type == 'remove') { // 移除操作
      for (var j = 0; j < imageData.length; j++) {
        if (code == imageData[j].imageDocType) {
          imageData[j].fileArray.splice(index, 1)
        }
      }
      //同时移除对象模型
      this.swichUpType(code,'remove',index)
    }

    filedata.push({ type: code, files: files })
    this.setState({
      filedata
    }, () => {
      if (type == 'add') {
        lrz(files[curIndex].url, { quality: 0.1 }).then((res) => {
          // 处理成功会执行
          console.log('--------------->压缩成功')
          let formData = res.formData
          this.uploadImage(formData, files[curIndex].file.name, code)
        })
      }
    })
  }

  // 每个item的理赔图片  初始化暂存理赔图片显示
  getFiles (type) {
    let filedata = this.state.filedata
    let files = []
    for (var i = 0; i < filedata.length; i++) {
      if (type == filedata[i].type) { files = filedata[i].files }
    }
    return files
  }

  handleSubmit (e) {
    //校验表单信息
    this.props.form.validateFields((error, values) => {
      var errorMap = {}
      if (error) {
        for (var key in error) {
          errorMap[key] = 1
        }
        T.showError('You can only input numbers here')
      } else {
         //支付类型 写死默认 后续修改 
        values['payMethod'] = '1'
        this.submitData(values)
      }

      this.setState({
        errorMap
      })
    })
  }

  dealClaimsApplicationImage () {
    let { imageData } = this.state
    let claimsApplicationImageDTOList = []
    for (let i = 0; i < imageData.length; i++) {
      for (var j = 0; j < imageData[i].fileArray.length; j++) {
        claimsApplicationImageDTOList.push({
          imageCode: imageData[i].fileArray[j].imageCode,
          imageName: imageData[i].fileArray[j].imageName,
          imageDocType: imageData[i].imageDocType
        })
      }
    }

    console.log(claimsApplicationImageDTOList)

    return claimsApplicationImageDTOList
  }

  validateImageData =()=> {
    let { imageData } = this.state
    const Lang = window.LangMessage || {}
    const docTypeMap = {
      1: Lang.web_ID_document || 'Identification Document (Front and Back)',
      2: this.isHealth ? (Lang.web_medaical_diagnosis || 'Medical Certificate / Medical Report with diagnosis') : (Lang.web_medaical_los || 'Loss List'),
      3: this.isHealth ? (Lang.web_medical_receipt || 'Medical Receipt') : (Lang.web_medical_orlos || 'Original loss or damage report issued by police, airline,hotel or relevant authorities')
    }
    for (var key in docTypeMap) { // 校验所有类型文件是否都选择 others除外
      let obj = T.getAttrObject(imageData, 'imageDocType', key)[0]
      if (!obj) {
        T.showError((Lang.please_select || 'Please Select') + ' ' + docTypeMap[key])
        return false
      }
      else if (obj && obj.fileArray) {
        if (obj.fileArray.length <= 0) {
          T.showError((Lang.please_select || 'Please Select') + ' ' + docTypeMap[key])
          return false
        }
        if (key === '1' && obj.fileArray.length < 2) {
          T.showError('The ' + docTypeMap[key] + ' should be two')
          return false
        }
      }
    }
    this.handleSubmit()
  }

  submitData (values) {
    //新版本信息提交
    const addModel = {
      claimApplication: this.infoValues, //上一步基本信息
        claimApplicationAccount:values, //银行信息
        ...this.FileModel //上传文件实体对象
    }
    console.log(JSON.stringify(addModel))
    const addDTO = T.fetch2({
      domainType:'apiclaim',
      url: API.submitClaimInfo.path,
      loading: true,
      data: addModel
    })
    addDTO.then((model)=>{
      if (model.code == '0'){
        actions.routing.push({
          pathname: '/poc-claim-success'
        })
      }
    })
  }

  onErrorClick (keyCode) {
    const { getFieldError } = this.props.form
    let msg = getFieldError(keyCode)
    if (msg) {
      T.showError(msg.join(','))
    }
  }

  render () {
    const { errorMap } = this.state
    const { getFieldProps } = this.props.form
    const Lang = window.LangMessage || {}
    const propertyList = [
      {
        name: Lang.web_ID_document || 'Identification Document (Front and Back)',
        type: 1,
        length: 2
      },
      {
        name: Lang.web_loss_list || 'Loss List',
        type: 2,
        length: 10
      },
      {
        name: Lang.web_original_loss || 'Original loss or damage report issued by police, airline,hotel or relevant authorities',
        type: 3,
        length: 10
      },
      {
        name: Lang.web_others || 'Others',
        type: 4,
        length: 10
      }
    ]

    const healthList = [
      { name: Lang.web_ID_document || 'Identification Document (Front and Back)',
        type: 1,
        length: 2
      },
      { name: Lang.web_medaical_diagnosis || 'Medical Certificate / Medical Report with diagnosis',
        type: 2,
        length: 10
      },
      { name: Lang.web_medical_receipt || 'Medical Receipt',
        type: 3,
        length: 10
      },
      { name: Lang.web_others || 'Others',
        type: 4,
        length: 10
      }
    ]

    const imgModel = this.infoValues.claimType === '2' ? healthList : propertyList

    return (<div className='my-claim poc-claim'>
      <div>
        <div className='f26 fc8 pl30  pb20 pt40' style={{ background: '#F7F9FB' }}>{Lang.web_upload_documents || 'Update Documents'}</div>
        <List>
          {imgModel.map((item, index) =>
            <ListItem key={index} className='mb20'>
              <div style={{ width: '100%' }} className='f30 fc6d clearfix mt10'>
                <p className='line-wrap fl' style={{ width: '80%' }}>{item.name}</p>
                <p className='line-wrap tar fr'>{this.getFiles(item.type).length || '0'}/{item.length}</p>
              </div>

              <ImagePicker
                length='5'
                files={this.getFiles(item.type)}
                onChange={(file, type, index) => this.onChange(file, type, index, item.type)}
                selectable={this.getFiles(item.type).length < item.length}
                accept='image/jpeg,image/png,image/bmp'
              />

            </ListItem>
          )}
        </List>
        <WhiteSpace />
        <p className='f26 fc9 pl30 pt30'>{Lang.web_pay_info || 'Payee Info'}</p>
        <List className='input-list'>
          <div className='clearfix f30 flex-item mt25 mb25' style={{ borderBottom: '1px solid #F2F2F2' }}>
            <div className='fc6d lh1 left-box'><div dangerouslySetInnerHTML={{ __html: Lang.web_pay_method || 'Payout Method' }} /></div>
            <div className='fc69 lh1'><div className='insure-box'>{Lang.web_bank_card || 'Bank Card'}</div></div>
          </div>
        </List>
        <List className='input-list mb100'>
          {this.keyCodes.map((item, index) =>
            <InputItem key={index}
              {...getFieldProps(item.keycode, {
                rules: item.rules
              })}
              maxLength={50}
              labelNumber={5}
              type={item.type || ''}
              error={errorMap[item.keycode]}
              onErrorClick={() => this.onErrorClick(item.keycode)}
              placeholder='Please Input'
            > <div dangerouslySetInnerHTML={{ __html: item.text }} /></InputItem>
          )}
        </List>
        <div style={{ height: '1.4rem', width: '100%' }} />
        <div className='bottom clearfix'>
          <Flex>
            <Flex.Item className='tac pt30 pb30 fcw f36 diy_background' style={{ flex: '1', borderRadius: '4px' }} onClick={this.validateImageData}>{Lang.text_submit || '提交'}</Flex.Item>
          </Flex>
        </div>
      </div>
    </div>
    )
  }
}

const AppForm = createForm()(App)
export default AppForm
